package br.com.itc.componentes.util
{
	import mx.utils.StringUtil;

	public class StringUtils {
		
		public static function isWhitespace(caracter:String):Boolean{
			return StringUtil.isWhitespace(caracter);
		}
		
		public static function substitute(str:String, rest:Array):String {
			return StringUtil.substitute(str, rest);
		}
		
		public static function trim(str:String):String {
			return StringUtil.trim(str);
		}
		
		public static function emptyToNull(str:String):String {
			var ret:String = StringUtil.trim(str);
			
			if(ret == "")
				return	null;
			else
				return ret;
		}
		
		public static function nullToString(str:String):String {
			if(str == null)
				return	"";
			else
				return StringUtil.trim(str);
		}
		
		public static function trimArrayElements(value:String, delimiter:String):String {
			return StringUtil.trimArrayElements(value, delimiter);
		}
		
		public static function right(str:String, len:Number):String {
			return str.substr(str.length - len);
		}
		
		public static function left(str:String, len:Number):String {
			return str.substr(0, len);
		}
		
		public static function contaCaracter(str:String, caracter:String):Number {
			var total:Number = 0;
			
			for(var i:int = 0; i < str.length; i++){
				if(str.substr(i, 1) == caracter)
					total++;
			}
			
			return total;
		}
		
		public static function completarCaracterEsquerda(valor:String, quant:int, caracter:String):String {
			var str:String = "";
			
			for(var i:int = 0; i < quant; i++) {
				str += caracter;
			}
			
			if(quant >= valor.length)
				return StringUtils.right(str + valor, quant);
			else
				return StringUtils.right(str + valor, valor.length);
		}
		
		public static function montarSequenciaCaracteres(caracter:String, quant:int):String {
			var str:String = "";
			
			for(var i:int = 0; i < quant; i++) {
				str += caracter;
			}
			
			return str;
		}
		
		public static function replace(input:String, replace:String, replaceWith:String):String
		{
			//change to StringBuilder
			var sb:String = new String();
			var found:Boolean = false;

			var sLen:Number = input.length;
			var rLen:Number = replace.length;

			for (var i:Number = 0; i < sLen; i++)
			{
				if(input.charAt(i) == replace.charAt(0))
				{   
					found = true;
					for(var j:Number = 0; j < rLen; j++)
					{
						if(!(input.charAt(i + j) == replace.charAt(j)))
						{
							found = false;
							break;
						}
					}

					if(found)
					{
						sb += replaceWith;
						i = i + (rLen - 1);
						continue;
					}
				}
				sb += input.charAt(i);
			}
			//TODO : if the string is not found, should we return the original
			//string?
			return sb;
		}
	}
}